import * as React from "react";
import { inject, observer } from "mobx-react";
import {
  Checkbox,
  Tooltip,
  Avatar,
  Card, Col, Row, Modal, Icon, Divider, Button, message,
} from 'antd';
import { History, Location } from 'history';
import EditModal from '../../../common/editModal/EditModal';
import { HomeStore } from '../../../../store';
import { finishedMessage, resetPasswordForAdmin, sendAnnouncement } from '../../../../basicData/api';
import { dateFormat } from '../../../../util/util'

interface IProps {
  history: History;
  location: Location;
  children?: AudioContextLatencyCategory;
  homeStore: HomeStore;
}

interface State {
  indeterminate: boolean,
  key: number,
  visible: boolean,
  values: any,
  userData: any,
}

//初始化state
const initialState: State = {
  indeterminate: false,
  key: 0,
  values: {},
  visible: false,
  userData: {},
};

type IState = Readonly<typeof initialState>;

@inject("homeStore")
@observer
class HomeInfo extends React.Component<IProps, IState> {
  state: IState = initialState;

  shouldComponentUpdate() {
    return true
  }

  /**
   * 阅读消息
   */
  notifyMessage = () => {
    const { checkedList } = this.props.homeStore;
    finishedMessage(checkedList).then((res: any) => {
      if (res.success) {
        // this.props.homeStore.readMessage(checkedList)
      }
    })
  }
  // 激活用户
  activeUser = (message: any) => {
    finishedMessage([message.messageId]).then((res: any) => {
      if (res.success) {
        this.props.homeStore.readMessage([message.messageId])
        this.props.history.push(`/home/users?Id=${message.content.Id}`)
      }
    })
  }

  // 重置密码
  resetPwd = (message: any) => {
    finishedMessage([message.messageId]).then((res: any) => {
      resetPasswordForAdmin(message.content.Id, '123qwe').then((res: any) => {
        if (res.success) {
          Modal.success({
            title: '重置密码成功',
            content: '用户初始密码为 123qwe ',
            okText: '确定'
          });
        }
      })
    })
  }

  handleCreate = (values: any) => {
    const param = JSON.stringify(values)
    sendAnnouncement(param).then((res: any) => {
      message.success('公告发布成功')
      this.setState({
        visible: false,
      });
    })
  }

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  }

  handleNew = () => {
    this.setState({
      visible: true,
    });
  }

  render() {
    const { messages, userAuth, isAdmin } = this.props.homeStore
    const { visible, values } = this.state
    const _this = this
    let messagelist;
    if (messages.length > 0) {
      messagelist = messages.slice(0)
    }

    const addConfig = [
      {
        type: 'input',
        name: '标题',
        key: 'title',
        rule: { required: true, message: '请输入标题' }
      },
      {
        type: 'textArea',
        name: '内容',
        key: 'content',
        rule: { required: true, message: '请输入内容' }
      },
    ]

    return (
      <div>
        <h1>欢迎使用权限管理后台</h1>
        {
          !isAdmin
          && <div>
            <Divider orientation='left'>系统公告</Divider>
            {
              messagelist
              ? <div style={{ padding: '10px 30px' }}>
                {
                  messagelist.map((message: any, index: number) => (
                    message.type === 'announcement'
                    && <div key={index} style={{marginBottom: 10, fontSize: '14px'}}>
                      <Icon type="notification" />
                      【{message.content ? message.content.title : '无标题'}】 {message.content && message.content.content}
                    </div>
                  ))
                }
              </div>
              : <p>{userAuth ? '暂无最新消息' : '用户暂未审批或没有添加权限，请联系管理员'}</p>
            }
          </div> 
        }
        {
          isAdmin
          && <div>
        {
          messagelist
            ? <div>
              {/* <div style={{ borderBottom: '1px solid #E9E9E9' }}>
                <Checkbox
                  indeterminate={this.state.indeterminate}
                  onChange={this.props.homeStore.onCheckAllChange}
                  checked={this.props.homeStore.checkAll}
                >
                  全选
                </Checkbox>
                <a onClick={this.notifyMessage} style={{ marginRight: 14 }}>
                  标为已读
                </a>
                <a onClick={this.handleNew} style={{ marginRight: 14 }}>
                  发布公告
                </a>
              </div>
              <br /> */}
              <Divider orientation='left'>系统公告</Divider>
              <div  style={{ paddingLeft: 30 }}>
                <Icon type="plus-circle" style={{color: '#1890ff', marginRight: 6}}/>
                <a onClick={this.handleNew}>
                  发布公告
                </a>
              </div>
              <div style={{  padding: '10px 30px' }}>
                {
                  messagelist
                    ? messagelist.map((message: any, index: number) => (
                      message.type === 'announcement'
                      && <div key={index} style={{marginBottom: 10, fontSize: '14px'}}>
                          <Tooltip placement="top" title='删除该条公告' >
                            <Icon
                              type="delete"
                              style={{marginRight: 10, color: 'red', cursor: 'pointer'}}
                              onClick={() => {this.props.homeStore.readMessage([message.messageId])}} 
                            />
                          </Tooltip>
                          <Icon type="notification" />
                          【{message.content ? message.content.title : '无标题'}】
                          {message.content && message.content.content}
                      </div>
                    ))
                    : '暂无最新消息'
                }
              </div>
              <Divider orientation='left'>用户消息</Divider>
              {/* <h3>用户消息</h3> */}
              <div style={{paddingLeft: 30}}>
                <Checkbox
                  indeterminate={this.state.indeterminate}
                  onChange={this.props.homeStore.onCheckAllChange}
                  checked={this.props.homeStore.checkAll}
                >
                  全选
                </Checkbox>
                <a onClick={this.notifyMessage} style={{ marginRight: 14 }}>
                  标为已读
                </a>
              </div>
              <Row style={{ padding: '10px 30px' }}>
                {messagelist.map((message: any, index: number) => (
                  message.type !== 'announcement'
                  && <Col xs={24} sm={12} md={8} lg={8} xl={6} key={index}>
                    <Card
                      title={
                        <Checkbox
                          value={message.messageId}
                          checked={message.isChecked}
                          onChange={_this.props.homeStore.onChange}
                        >
                          <Avatar
                            size="large"
                            style={{ backgroundColor: (message.type === 'newUser') ? "#76b39d" : "#fab95b" }}
                          >
                            {message.content.UserName ? message.content.UserName.slice(0, 1) : ''}
                          </Avatar>
                        </Checkbox>
                      }
                      extra={
                        message.type === 'newUser'
                          ? <Tooltip placement="top" title='跳转至用户管理，审批用户'>
                            <a onClick={() => this.activeUser(message)}><Icon type="user-add" />审批用户</a>
                          </Tooltip>
                          : <Tooltip placement="top" title='将该用户密码重置为123qwe'>
                            <a onClick={() => this.resetPwd(message)}><Icon type="user-add" />重置密码</a>
                          </Tooltip>
                      }
                    >
                      <p>{message.type === 'newUser' ? '【新用户】' : '【重置密码】'}</p>
                      <div style={{marginBottom: 4}}>用户编码：{message.content.UserCode}</div>
                      <div style={{marginBottom: 4}}>用户名称：{message.content.UserName}</div>
                      <div style={{marginBottom: 4}}>真实姓名：{message.content.UserRealName || '--'}</div>
                      <div style={{marginBottom: 4}}>手机号码：{message.content.TelNumber || '--'}</div>
                      <div style={{marginBottom: 4}}>电子邮箱：{message.content.Email || '--'}</div>
                      <div style={{marginBottom: 4}}>联系地址：{message.content.Address || '--'}</div>
                      <div style={{marginBottom: 4}}>所属公司：{message.content.SubordinateCompany ? message.content.SubordinateCompany.CompanyName : '--'}</div>
                      <div style={{marginBottom: 4}}>注册时间：{dateFormat(message.content.CreationTime)}</div>
                      <div style={{marginBottom: 4}}>用户留言：{message.content.UserRemarks || '--'}</div>
                    </Card>
                  </Col>
                ))}
              </Row>
            </div>
            : <p>{userAuth ? '暂无最新消息' : '用户暂未审批或没有添加权限，请联系管理员'}</p>
          }
          </div>
        }
        
        <EditModal
          title='发布公告'
          isNew={true}
          values={values}
          visible={visible}
          onCancel={this.handleCancel}
          onCreate={this.handleCreate}
          editconfig={addConfig}
        />
      </div>
    );
  }
}

export default HomeInfo